/**
 * 登录安全工具类
 * 提供防暴力破解、频率限制等安全功能
 */
class LoginSecurity {
	constructor() {
		this.storagePrefix = 'login_security_';
		this.maxAttempts = 5;
		this.lockDuration = 30; // 30秒
		this.minInterval = 2000; // 2秒
		this.captchaThreshold = 3; // 3次失败后显示验证码
	}

	/**
	 * 获取存储键名
	 * @param {string} key 
	 * @returns {string}
	 */
	getStorageKey(key) {
		return this.storagePrefix + key;
	}

	/**
	 * 检查是否被锁定
	 * @param {string} identifier 标识符（如IP或用户名）
	 * @returns {boolean}
	 */
	isLocked(identifier) {
		const lockStart = uni.getStorageSync(this.getStorageKey(`lock_${identifier}`)) || 0;
		if (lockStart === 0) return false;

		const now = Date.now();
		const elapsed = Math.floor((now - lockStart) / 1000);
		return elapsed < this.lockDuration;
	}

	/**
	 * 获取剩余锁定时间
	 * @param {string} identifier 
	 * @returns {number}
	 */
	getRemainingLockTime(identifier) {
		const lockStart = uni.getStorageSync(this.getStorageKey(`lock_${identifier}`)) || 0;
		if (lockStart === 0) return 0;

		const now = Date.now();
		const elapsed = Math.floor((now - lockStart) / 1000);
		return Math.max(0, this.lockDuration - elapsed);
	}

	/**
	 * 锁定账户
	 * @param {string} identifier 
	 */
	lockAccount(identifier) {
		uni.setStorageSync(this.getStorageKey(`lock_${identifier}`), Date.now());
	}

	/**
	 * 解锁账户
	 * @param {string} identifier 
	 */
	unlockAccount(identifier) {
		uni.removeStorageSync(this.getStorageKey(`lock_${identifier}`));
		uni.removeStorageSync(this.getStorageKey(`attempts_${identifier}`));
		uni.removeStorageSync(this.getStorageKey(`last_attempt_${identifier}`));
	}

	/**
	 * 增加登录尝试次数
	 * @param {string} identifier 
	 * @returns {object} 返回尝试次数和是否需要显示验证码
	 */
	incrementAttempts(identifier) {
		const attempts = (uni.getStorageSync(this.getStorageKey(`attempts_${identifier}`)) || 0) + 1;
		uni.setStorageSync(this.getStorageKey(`attempts_${identifier}`), attempts);

		// 检查是否需要锁定
		if (attempts >= this.maxAttempts) {
			this.lockAccount(identifier);
		}

		return {
			attempts,
			showCaptcha: attempts >= this.captchaThreshold,
			isLocked: attempts >= this.maxAttempts
		};
	}

	/**
	 * 获取当前尝试次数
	 * @param {string} identifier 
	 * @returns {number}
	 */
	getAttempts(identifier) {
		return uni.getStorageSync(this.getStorageKey(`attempts_${identifier}`)) || 0;
	}

	/**
	 * 检查登录频率
	 * @param {string} identifier 
	 * @returns {boolean}
	 */
	checkFrequency(identifier) {
		const lastAttempt = uni.getStorageSync(this.getStorageKey(`last_attempt_${identifier}`)) || 0;
		const now = Date.now();
		
		if (now - lastAttempt < this.minInterval) {
			return false;
		}

		uni.setStorageSync(this.getStorageKey(`last_attempt_${identifier}`), now);
		return true;
	}

	/**
	 * 生成验证码
	 * @param {number} length 验证码长度
	 * @returns {string}
	 */
	generateCaptcha(length = 4) {
		const chars = '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ';
		let result = '';
		for (let i = 0; i < length; i++) {
			result += chars.charAt(Math.floor(Math.random() * chars.length));
		}
		return result;
	}

	/**
	 * 验证验证码
	 * @param {string} input 用户输入
	 * @param {string} expected 期望值
	 * @returns {boolean}
	 */
	validateCaptcha(input, expected) {
		return input.toUpperCase() === expected.toUpperCase();
	}

	/**
	 * 获取设备指纹
	 * @returns {string}
	 */
	getDeviceFingerprint() {
		try {
			const systemInfo = uni.getSystemInfoSync();
			const fingerprint = [
				systemInfo.platform,
				systemInfo.system,
				systemInfo.model,
				systemInfo.screenWidth,
				systemInfo.screenHeight
			].join('|');
			return btoa(fingerprint);
		} catch (e) {
			return 'unknown';
		}
	}

	/**
	 * 记录安全日志
	 * @param {string} action 操作类型
	 * @param {object} data 相关数据
	 */
	logSecurityEvent(action, data = {}) {
		const log = {
			timestamp: Date.now(),
			action,
			data,
			deviceFingerprint: this.getDeviceFingerprint()
		};

		const logs = uni.getStorageSync(this.getStorageKey('security_logs')) || [];
		logs.push(log);

		// 只保留最近100条日志
		if (logs.length > 100) {
			logs.splice(0, logs.length - 100);
		}

		uni.setStorageSync(this.getStorageKey('security_logs'), logs);
	}

	/**
	 * 清理过期的安全数据
	 */
	cleanupExpiredData() {
		const now = Date.now();
		const keys = uni.getStorageInfoSync().keys;
		
		keys.forEach(key => {
			if (key.startsWith(this.storagePrefix)) {
				const data = uni.getStorageSync(key);
				if (data && typeof data === 'number') {
					// 清理超过24小时的锁定记录
					if (now - data > 24 * 60 * 60 * 1000) {
						uni.removeStorageSync(key);
					}
				}
			}
		});
	}
}

// 创建单例实例
const loginSecurity = new LoginSecurity();

export default loginSecurity; 